package com.llkj.qingnianguoxue.music;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.jm.chat.pickerimage.utils.StringUtil;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.bean.Response;
import com.llkj.qingnianguoxue.db.LocalMusicBean;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.lrcview.LrcView;
import com.llkj.qingnianguoxue.playservice.Music;
import com.llkj.qingnianguoxue.playservice.OnlineMusic;
import com.llkj.qingnianguoxue.playservice.PlayOnlineMusic;
import com.llkj.qingnianguoxue.playservice.SystemUtils;
import com.llkj.qingnianguoxue.util.DialogUtil;
import com.llkj.qingnianguoxue.util.DisplayUtil;
import com.llkj.qingnianguoxue.util.FileOperation;
import com.llkj.qingnianguoxue.util.FileProvider7;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.ImageLoadingUtil;
import com.llkj.qingnianguoxue.util.MyShare;
import com.llkj.qingnianguoxue.util.SelectPictureUtil;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.functions.Action1;

import static com.llkj.qingnianguoxue.http.HttpMethod.HTTP_KOJI_PRESERVATION;

/**
 * 录制完成
 */
public class RecordCompleteActivity extends BaseActivity implements DialogUtil.DialogClickListener,MyShare.ShareResultCallback
        ,DialogUtil.ClickOptionListener,SelectPictureUtil.SelectPictureResultCallback{

    @BindView(R.id.music_title)
    View titleView;//
    @BindView(R.id.ivMusicBg)
    protected ImageView mIvMusicBg;//背景
    @BindView(R.id.iv_music_corver)
    protected ImageView mIvMusicCorver;//封面
    @BindView(R.id.tv_music_name)
    protected TextView mTvMusicName;//音乐名
    @BindView(R.id.tv_count)
    protected TextView mTvCount;//听过人数
    @BindView(R.id.tvPlayerCurrentTime)
    protected TextView mTvCurrentTime;//当前播放时间
    @BindView(R.id.tvPlayerDuration)
    protected TextView mTvPlayerDuration;//总播放时长
    @BindView(R.id.ll_repeat)
    LinearLayout mLLRepeat;//重唱
    @BindView(R.id.ll_share)
    LinearLayout mLLShare;//分享
    @BindView(R.id.tvSave)
    TextView mBtnCenter;//保存，播放
    @BindView(R.id.sbPlayerProgress)
    protected SeekBar mSeekBar;//播放进度
    @BindView(R.id.lrc_view_full)
    protected LrcView mLrcView;//歌词显示
    private File mLrcFile;//歌词文件

    private Dialog mDialogTip;//是否展示此作品弹框
    private int mClickType;//1保存，2分享
    private int mPlayDuration,mLastProgress;//播放时长,播放进度
    private String mRecordPath;//录制内容本地路径
    private String mMusicDescription,mLinkUrl;

    private String mMusicId;//伴奏id
    private String mMusicCorverUrl;//伴奏音乐封面图片
    private String mMusicName;//伴奏音乐名称
    private String mCountSing;//演唱人数
    private String mMusicBgPath;//背景图片
    private String mMusicUrl;//伴奏音乐
    private String mOriginalMusicUrl;//原唱音乐
    private String mMusicLrcUrl;//歌词url
    private int mShareType = -1;//分享方式1微信好友，2微信朋友圈，3新浪，4QQ好友，5本地好友
    private int mIsShowType;//1立即展示，0暂不展示
    private boolean isPublish = false,isSaveLocal = false;//是否发布,是否保存本地
    private String mCategoryType;//判断来自哪个界面

    private boolean isPermissions;//请求存储
    private SelectPictureUtil mSelectPictureUtil;//选择图片
    private File cameraFile;//拍照缓存地址

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_comlete);
        setTitle("", true, TITLE_TYPE_IMG, R.drawable.icon_back_white, false,-1,-1);

        ButterKnife.bind(this);
        new RxPermissions(this)
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        isPermissions = aBoolean;
                    }
                });

        getIntentData();

        loadLrcFile();
        initView();
//        if("1".equals(mCategoryType)){
            playMusic();
//        }
    }

    private void getIntentData(){
        Intent intent = getIntent();
        mCategoryType = intent.getStringExtra("categoryType");
        if("1".equals(mCategoryType)){
            mLLRepeat.setVisibility(View.GONE);
            mLLShare.setVisibility(View.GONE);
            mBtnCenter.setText("播放");
            mMusicBgPath = intent.getStringExtra("musicBgPath");//保存背景图片
        }else{
            mRecordPath = intent.getStringExtra("recordPath");//录制本地路径
            mMusicId = intent.getStringExtra("musicId");//伴奏id
            mMusicUrl = intent.getStringExtra("musicUrl");//伴奏音乐
            mOriginalMusicUrl = intent.getStringExtra("musicOriginalUrl");//原唱音乐
        }
        mMusicLrcUrl = intent.getStringExtra("musicLrcUrl");//歌词url
        mMusicCorverUrl = intent.getStringExtra("musicCoverUrl");//伴奏音乐封面图片
        mMusicName = intent.getStringExtra("musicName");//伴奏音乐名称
        mCountSing = intent.getStringExtra("countSing");//演唱人数
        mRecordPath = intent.getStringExtra("recordPath");//录制本地路径

    }

    private void initView(){
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT,rlTitle,R.color.transparent);
//        systemBarTintManager.setStatusBarTintColor(ContextCompat.getColor(this, R.color.transparent));
        rlTitle.setBackgroundColor(ContextCompat.getColor(this, R.color.transparent));
        titleLineBottom.setVisibility(View.GONE);
        tvTitle.setTextColor(ContextCompat.getColor(this, R.color.white));

        ImageLoadingUtil.loadImgGlideRoundCenterCrop(mIvMusicCorver,mMusicCorverUrl);
        mTvMusicName.setText(mMusicName);
        mTvCount.setText(mCountSing+"人唱过");

        if(!StringUtils.isEmpty(mMusicBgPath)){
            ImageLoadingUtil.loadingUrl(mIvMusicBg,mMusicBgPath);
        }else{
            ImageLoadingUtil.loadLocalImg(mIvMusicBg,R.drawable.icon_record_bg);
        }

        mDialogTip = DialogUtil.dialogConfirm(this,"是否将作品展示在个\n人主页上?",null,"暂不展示","立即展示",this);

        mSelectPictureUtil = new SelectPictureUtil(this,this);
        mSelectPictureUtil.setCropWidthHeight(DisplayUtil.getDensityWdith(this),DisplayUtil.getDensityHeight(this));

        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //进度变化调用
                Log.e("Log","===onProgressChanged()=="+progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //开始拖动调用
                Log.e("Log","===onStartTrackingTouch()=="+seekBar.getProgress());
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //拖动停止调用
                Log.e("Log","===onStopTrackingTouch()=="+seekBar.getProgress());
                int progress = mPlayDuration*seekBar.getProgress()/100;
                getPlayService().seekTo(progress);

                mLrcView.updateTime(progress);
                mLrcView.loadLrc(mLrcFile);
            }
        });
    }

    private void loadLrcFile(){
        OnlineMusic onlineMusic = new OnlineMusic();
        //这两个字段是用于处理歌词文件名的
        onlineMusic.setArtist_name("lrc");
        onlineMusic.setTitle(mMusicId);
        //这个是下载歌词的链接
        onlineMusic.setLrclink(mMusicLrcUrl);
//        onlineMusic.setMusicUrl(mMusicUrl);
//        onlineMusic.setOrgMusicUrl(mOriginalMusicUrl);
        play(onlineMusic);
    }

    @OnClick({R.id.ll_repeat, R.id.tvSave, R.id.ll_share})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.ll_repeat://重唱
                Intent intent = new Intent();
                intent.putExtra("result","repeat");
                setResult(RESULT_OK,intent);
                finish();
                break;
            case R.id.tvSave://保存
                if("1".equals(mCategoryType)){
//                    mLastProgress = 0;
                    getPlayService().playPause();
                    if(getPlayService().isPlaying()){//暂停
                        mBtnCenter.setText("暂停");
                    }else{
                        mBtnCenter.setText("播放");
                    }
                    return;
                }
                mClickType = 1;
                showPhotoPictureDialog();
                break;
            case R.id.ll_share://分享
                mClickType = 2;
                showPhotoPictureDialog();
                break;
        }
    }

    private void showPhotoPictureDialog(){
        DialogUtil.showPhotoPictureDialog(this, new DialogUtil.DialogClickListener() {
            @Override
            public void dialogClick(int type) {
                switch (type) {
                    case 1://拍照
                        if (isPermissions) {
                            mSelectPictureUtil.takePhoto();
                        } else {
                            ToastUtil.makeLongText(RecordCompleteActivity.this, getResources().getString(R.string.permission_camera));
                        }
                        break;
                    case 2://相册
                        mSelectPictureUtil.album();
                        break;
                    case 4://取消
                        clickType();
                        break;
                }
            }
        }).show();
    }

    private void clickType(){
        if(mClickType == 1){
            mDialogTip.show();
        }else if(mClickType == 2){
            mDialogTip.show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mSelectPictureUtil.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onCropResult(File file) {
        cameraFile = file;
        mMusicBgPath = cameraFile.getAbsolutePath();
        ImageLoadingUtil.loadingUrl(mIvMusicBg, mMusicBgPath);

        clickType();
    }

    //保存默认图片
    private void saveDefaultPic(){
        if(StringUtil.isEmpty(mMusicBgPath)){
            try {
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon_record_bg);;
                cameraFile = FileOperation.saveBgFile(this, bitmap);
                mMusicBgPath = cameraFile.getAbsolutePath();
                bitmap.recycle();
                bitmap= null;
            }catch (Exception e){}
        }
    }

    private void playMusic(){
        loadWaitDialog();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Music music = new Music();
                music.setPath(mRecordPath);
                getPlayService().seekTo(0);
                getPlayService().play(music);
            }
        }, 1000);
    }

    @Override
    public void dialogClick(int type) {
        mIsShowType = type;//1立即展示，0暂不展示
        if(type==1){//立即展示，这里将调用发布接口
            publishMusic();
        }else if(mClickType==1){//暂不展示，判断点击本地保存按钮，执行保存本地
            if(isSaveLocal){
                ToastUtil.makeLongText(this,"已经保存本地了");
                return;
            }
            saveRecordData();
        }else if(mClickType==2){//点击分享，暂不展示，弹出分享弹框，选择分享方式
            DialogUtil.showShareMusicDialog(this,this);
        }
    }

    /**
     * 录制完成，保存本地
     */
    private void saveRecordData(){
        LocalMusicBean musicBean = new LocalMusicBean();
        musicBean.setRecordMusicPath(mRecordPath);//录制本地路径
        musicBean.setMusicId(mMusicId);//伴奏id
        musicBean.setMusicCorverUrl(mMusicCorverUrl);//伴奏音乐封面图片
        musicBean.setMusicName(mMusicName);//伴奏音乐名称
        musicBean.setCountSing(mCountSing);//演唱人数
        saveDefaultPic();
        musicBean.setMusicBgPath(mMusicBgPath);//背景图片
        musicBean.setMusicUrl(mMusicUrl);//伴奏音乐
        musicBean.setOriginalMusicUrl(mOriginalMusicUrl);//原唱音乐
        musicBean.setMusicLrcUrl(mMusicLrcUrl);//歌词url
        if (musicBean.save()) {
            isSaveLocal = true;
            //存储成功
            shareResultCallBack(1);
            Log.e("Log","===数据库存储成功");
        } else {
            //存储失败
            Log.e("Log","===数据库存储失败");
        }
    }

    @Override
    public void clickOptionResopnse(int option) {
        mShareType = option;
        if(isPublish){//已发布了，直接调起三方分享
            DialogUtil.shareParams(this,mShareType,mMusicName,mMusicDescription,mMusicCorverUrl,mLinkUrl,this);
        }else{
            //这里调用发布接口，然后在接口成功回调中调起三方分享和本地分享
            publishMusic();
        }
    }

    @Override
    public void shareResultCallBack(int result) {
        //result  1成功，2失败，3取消，
        if(result==1){
            Intent intent = new Intent();
            intent.putExtra("result","finish");
            setResult(RESULT_OK,intent);
            finish();
        }else if(result==4){//我的圈子
            DialogUtil.shareCircle(this,mMusicId,mMusicName,mCountSing,mMusicCorverUrl,mRecordPath);
        }
    }

    private String formatTime(long time) {
        return SystemUtils.formatTime("mm:ss", time);
    }

    @Override
    public void onPublish(int progress) {
        super.onPublish(progress);
        if(mPlayDuration<=0){
            mPlayDuration = getPlayService().getMediaPlayer().getDuration();
            mTvPlayerDuration.setText(formatTime(mPlayDuration));
        }

        if(mPlayDuration>0){
            mSeekBar.setProgress(progress*100/mPlayDuration);
        }

        //更新当前播放时间
        if(progress-mLastProgress>=1000){
            mLastProgress = progress;
            mTvCurrentTime.setText(formatTime(progress));
        }

        mLrcView.updateTime(progress);

        if(progress==mPlayDuration){//播放完成

        }
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        super.onPrepared(mp);
        mPlayDuration = mp.getDuration();
        mTvPlayerDuration.setText(formatTime(mPlayDuration));
        dismissWaitDialog();
    }

    private void publishMusic(){
        File fileBgImg = null,fileMusic=null;
        try {
            saveDefaultPic();
            fileBgImg = new File(mMusicBgPath);
        }catch (Exception e){}

        try {
            fileMusic = new File(mRecordPath);
            if(fileMusic!=null && fileMusic.exists()){
                loadWaitDialog();
                String isShow = mIsShowType==1?"1":"2";
                HttpMethod.kojiPreservation(this,this,mMusicId,isShow,fileMusic,fileBgImg);
            }else{
                ToastUtil.makeLongText(this,"对不起，您录制的文件发生错误，不能上传");
            }
        }catch (Exception e){
            ToastUtil.makeLongText(this,"对不起，您录制的文件发生错误，不能上传");
        }
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if(method==HTTP_KOJI_PRESERVATION){
            Response response = GsonUtil.GsonToBean(data,Response.class);
            if(response!=null){
                mLinkUrl = String.format(HttpMethod.SHARE_USERKOJI,response.getSing_id());
            }

            //mClickType 1保存，2分享
            isPublish = true;
            if(mClickType==2 && mIsShowType==1){//点击分享，立即展示,弹出分享弹框
                DialogUtil.showShareMusicDialog(this,this);
            }else if(mClickType==1 && mIsShowType==1){//点击保存，立即展示
                ToastUtil.makeLongText(this,"您的作品已发布，并在个人主页上展示");
                myFinish();
            }else if(mClickType==2 && mShareType!=-1){//点击分享，暂不展示，弹框选择分享方式，调起三方分享
                DialogUtil.shareParams(this,mShareType,mMusicName,mMusicDescription,mMusicCorverUrl,mLinkUrl,this);
            }

        }
    }

    private void play(OnlineMusic onlineMusic) {
        new PlayOnlineMusic(this, onlineMusic) {
            @Override
            public void onPrepare() {}

            @Override
            public void onExecuteSuccess(Music music) {
                dismissWaitDialog();
            }

            @Override
            public void onExecuteFail(Exception e) {}
        }.setRefuseMobileNetListener(new PlayOnlineMusic.RefuseUserMobileNEtListener() {
            @Override
            public void refuseMobileNet() {
                dismissWaitDialog();
                myFinish();
            }
        }).setDownloadListener(new PlayOnlineMusic.DownloadFileListener() {
            @Override
            public void downloadFileListener(int type, int state, float progress,File file) {
                switch (type){
                    case 0:
                        if(state==1){//歌词下载成
                            mLrcFile = file;
                            mLrcView.loadLrc(file);
                        }else if(state==2 && progress<2){//歌词下载中
                            mLrcView.setLabel("正在下载歌词...");
                        }else if(state==3){
                            mLrcView.setLabel("暂无歌词");
                        }
                        break;
                }
            }
        }).execute();
    }
}
